define(function (require, exports, module) {
    var PDFRect = WebPDF.PDFRect;
    var RectUtils = WebPDF.RectUtils;



    WebPDF.TypewriterAnnotHandler = function (readerApp,annotType,annotHandlerManager) {
        this.readerApp = readerApp;
        this.annotType = annotType;
      //  this.typewriterAnnotPlugin = typewriterAnnotPlugin;
        this.annotHandlerManager = annotHandlerManager;
        this.init(readerApp,annotHandlerManager.getUIManager());
      //  this.currentPageIndex = -1;
        //this.currentAnnotName = null;
      //  this.annotUIManager = annotUIManager;
    };

    WebPDF.TypewriterAnnotHandler.prototype =
    {
        getType: function () {
            return this.annotType;
        },
        canAnswer: function (annot) {
            if (!this.readerApp.isEditable())
                return false;
            var annotType = annot.getIT();
            if (!this.isTypewritersType(annotType) || !annot.isVisible())
                return false;
            var tool = this.readerApp.getCurToolHandler();
            if (tool != null) {
                var csToolName = tool.getName();
                if (csToolName === WebPDF.Tools.TOOL_NAME_SELANNOT || csToolName === WebPDF.Tools.TOOL_NAME_HAND ||
                    csToolName.toLowerCase() === this.annotType.toLowerCase()) {
                    return true;
                }
            }
            return false;
        },
        canMove: function (subType) {
            if (this.annotScale) return false;
            return true;
        },

        isTypewritersType: function(annotType)
        {
            if (annotType.toLowerCase() == WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_TYPEWRITER.toLowerCase() /*||
            annotType.toLowerCase() == WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_TEXTBOX.toLowerCase() ||
            annotType.toLowerCase() == WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_CALLOUT.toLowerCase() */)
                return true;
            else
                return false;
        },

        moveAnnot: function (pageView, selectedAnnot, offsetX, offsetY, newPosX, newPosY) {
            var annotName = selectedAnnot.getAnnotName();
            var pdfPage = pageView.getPDFPage();
            var annotUIManager = this.annotHandlerManager.getUIManager();
            var annotDivID = annotUIManager.getAnnotDivID(pageView, annotName);
            var jqAnnotDiv = $("#" + annotDivID);
            jqAnnotDiv.css({
                left: newPosX + "px",
                top: newPosY + "px"
            });
            var annotRectDivID = annotUIManager.getTypewriterAnnotRectDivID(pageView, annotName);
            var jqAnnotRect = $("#" + annotRectDivID);
            var pageRotate = (pdfPage.getPageRotate() * 90) % 360;
            var rotate = (selectedAnnot.getRotate() % 360 + 360) % 360;
            if (pageRotate != rotate) {
                var realRotate = Math.abs(rotate - pageRotate);
                var srcRect = new WebPDF.PDFRect(newPosX, newPosY, newPosX + jqAnnotRect.width(), newPosY + jqAnnotRect.height());
                switch (realRotate) {
                    case 90:
                    {
                        newPosX = srcRect.left;
                        newPosY = srcRect.bottom;
                    }
                        break;
                    case 180:
                    {
                        newPosX = srcRect.right;
                        newPosY = srcRect.bottom;
                    }
                        break;
                    case 270:
                    {
                        newPosX = srcRect.right;
                        newPosY = srcRect.top;
                    }
                        break;
                    default:
                        break;
                }
            }
            if (WebPDF.Environment.ie8OrLower) {
                jqAnnotRect.parent().css({
                    left: newPosX + "px",
                    top: newPosY + "px"
                });
            }
            else {
                jqAnnotRect.css({
                    left: newPosX + "px",
                    top: newPosY + "px"
                });
            }
        },
        
         resizeAnnot : function(annot, annotEle, offsetX, offsetY,direction){
        	var docView = _readerApp.getDocView();        	
            var pageIndex = parseInt(annotEle.attr("page-index"));
            var annotName = annotEle.attr("annot-name");
			var pageView = docView.getPageView(pageIndex);       
            
        	var pageViewWidth = pageView.getPageViewWidth();
        	var pageViewHeight = pageView.getPageViewHeight();
        	var curLeft = parseInt(annotEle.css("left"));
        	var curTop = parseInt(annotEle.css("top"));
        	var curWidth = annotEle.width();
        	var curHeight = annotEle.height();
        	
        	var maxWidth = pageViewWidth
			var maxHeight = pageViewHeight;
            var width, height; 
            var top = curTop; 
            var left = curLeft;
             
        	if(direction=="sw"){        		
                offsetY = Math.max(20 - curHeight, offsetY);
                offsetX = Math.max(0 - curLeft, offsetX);
                offsetY = Math.min(maxHeight - curTop - curHeight, offsetY);
                offsetX = Math.min(curWidth - 20, offsetX);     
                height = curHeight + offsetY;
                width = curWidth - offsetX;  
                left =  curLeft + offsetX; 
        	}
        	else if(direction == "nw"){
                offsetY = Math.max(0 - curTop, offsetY);
                offsetX = Math.max(0 - curLeft, offsetX);
                offsetY = Math.min(curHeight - 20, offsetY);
                offsetX = Math.min(curWidth - 20, offsetX);                     		
                height = curHeight - offsetY;
                width = curWidth -offsetX;    
                top = curTop + offsetY;
                left =  curLeft + offsetX;              
        	}
            else if (direction == "ne"){
                offsetY = Math.max(0 - curTop, offsetY);                
                offsetY = Math.min(curHeight - 20, offsetY);               
                offsetX = Math.max(20 - curWidth, offsetX);
                offsetX = Math.min(maxWidth - curLeft - curWidth, offsetX);                                 		
                height = curHeight - offsetY;
                width = curWidth + offsetX;    
                top = curTop + offsetY;      
            }// se
            else {          
                offsetY = Math.max(20 - curHeight, offsetY);
                offsetX = Math.max(20 - curWidth, offsetX);
                offsetY = Math.min(maxHeight - curTop - curHeight, offsetY);
                offsetX = Math.min(maxWidth - curLeft - curWidth, offsetX);                
                var width = curWidth + offsetX;
        	    var height = curHeight + offsetY;            
            }
		
           
            var obj = annotEle.find("textarea");
            var jqTextAreaParent = obj.parent();
            obj.css({"width": width + "px", "height": height + "px"});     
            jqTextAreaParent.css({"width": width + "px", "height": height + "px"});             
			annotEle.css({"width": width + "px", "height": height+ "px"}); 
			if(direction == "sw"){
				annotEle.css("left", left + 'px');
			}
            else if(direction == "nw"){                
				annotEle.css("top", top + 'px');
                annotEle.css("left", left + 'px');
			}	
             else if (direction == "ne"){
                annotEle.css("top", top + 'px');
             }
        },

        deleteAnnot: function (pageView, annot) {
            var annotName = annot.getAnnotName();
            var annotUIManager = this.annotHandlerManager.getUIManager();
            var annotDivID = annotUIManager.getAnnotDivID(pageView, annotName);
            $("#" + annotDivID).remove();
            var annotShowDivID = annotUIManager.getTypewriterAnnotDivID(pageView, annotName);
            $("#" + annotShowDivID).remove();
        },
        onDraw: function (pageView,  annot, isRedraw, extraScale) {
        },
        onSelected: function(pageView,  annot ){           
            var annotName = annot.getAnnotName();
            var annotUIManager = this.annotHandlerManager.getUIManager();
            var annotDivID = annotUIManager.getAnnotDivID(pageView, annotName);
            $("#" + annotDivID).addClass("fwr-annot-selected");
            /*$(".fwr_annot_selected").jeegoocontext(_MenuID, {
             onSelect: function (e, context) { return _self.OnSelect($(this)); }
             });*/
            return true;
        },
        onDeSelected: function(pageView, annot){           
            var annotName = annot.getAnnotName();
            var annotUIManager = this.annotHandlerManager.getUIManager();
            var annotDivID = annotUIManager.getAnnotDivID(pageView, annotName);
            $("#" + annotDivID).removeClass("fwr-annot-selected");
            /*$(".fwr_annot_selected").jeegoocontext(_MenuID, {
             onSelect: function (e, context) { return _self.OnSelect($(this)); }
             });*/
            return true;
        },
        onFocus: function(pageView, annot){
            //call TypeWriter :: onFocus
        },
        onLButtonDown: function (pageView, annot ,event) {            
           if ($(event.target).hasClass("fwr-annot-scaleImg")){                
                   this.annotScale = true;
                   this.direction = $(event.target).attr("direction");
                   this.curMouseX = event.pageX;
                   this.curMouseY = event.pageY;
                   this.curObject = $(event.target).parent();
                   return false;
            }                     
            return this.onSelected(pageView,annot);
        },

        onMouseMove: function(annot, event){          
            if(this.annotScale){
                var offsetX = event.pageX - this.curMouseX;
                var offsetY = event.pageY - this.curMouseY;              
              
                if (Math.sqrt(offsetX * offsetX + offsetY * offsetY) > 6){
                    this.curMouseX = event.pageX;
                    this.curMouseY = event.pageY;   
                    this.resizeAnnot(annot, this.curObject, offsetX, offsetY, this.direction);
                }
                return true;
            }   
        },        
        onLButtonUp: function(annot, pageView, event){
            if (this.annotScale){
                var annotEle = this.curObject;
                var annotDocRect = {};
                annotDocRect.left = parseFloat(annotEle.css("left"));
                annotDocRect.top  = parseFloat(annotEle.css("top"));
                annotDocRect.right =  annotDocRect.left + annotEle.width();
                annotDocRect.bottom = annotDocRect.top + annotEle.height();                
                var annotPDFRect = pageView.docToPDF(annotDocRect,true);               
                annot.setRect(annotPDFRect);
               this.annotScale = false;
            }           
        },
        
        onLButtonDblClk: function (pageView, annot, event) {
//            this.annotHandlerManager.clearSelection();
            this.onTypewriterAnnotEdit(pageView, annot);
        },

        onMouseOver: function(pageView, annot, event){
           // this.annotHandlerManager.getMarkupAnnotHandler().onMouseOver(pageView, annot,event);
        },
        onMouseLeave : function (pageView, annot, event) {
            //this.annotHandlerManager.getMarkupAnnotHandler().onMouseLeave(pageView, annot,event);
        },
        onUpdatePosition: function(pageView, annot, visibleRect){
            var pdfPage = pageView.getPDFPage();
            var annotPDFRect = annot.getRect();
            var annotDocRect = pageView.pdfToDoc(annotPDFRect, true);
            var annotUIManager = this.annotHandlerManager.getUIManager();
            var annotShowDivID = annotUIManager.getTypewriterAnnotRectDivID(pageView, annot.getAnnotName());

            var nPt2Pixel = this.readerApp.getPixelsPerPoint();
            var nScale = pageView.getScale();
            var fontsize = annot.getFontSize() * nPt2Pixel * nScale;
            var annotDivID = annotUIManager.getAnnotDivID(pageView, annot.getAnnotName());
            var jqAnnotDiv = $("#" + annotDivID);
            var fontScale = nScale * 1;
            var lineHeight = annot.getLineHeight() * nPt2Pixel * fontScale;
            jqAnnotDiv.css({
                left: annotDocRect.left,
                top: annotDocRect.top,
                width: WebPDF.RectUtils.width(annotDocRect)+ "px",
                height: WebPDF.RectUtils.height(annotDocRect)+ "px"
            });

            $("#" + annotShowDivID).parent().css({                
                width: WebPDF.RectUtils.width(annotDocRect)+ "px",
                height: WebPDF.RectUtils.height(annotDocRect)+ "px"
            })
         
            $("#" + annotShowDivID).css({                
                width: WebPDF.RectUtils.width(annotDocRect)+ "px",
                height: WebPDF.RectUtils.height(annotDocRect)+ "px",            
                "line-height": lineHeight + "px",
                "font-size": fontsize + "px"
            });

        },

        _addAndRemoveChangeValueEvent: function (obj, bAdd) {
            //IE
        	var _self = this;
            if (WebPDF.Environment.ie) {
                if (bAdd) {
                    obj.attachEvent("onpropertychange", function(){_self._spellCheck(_self.readerApp)});
                } else {
                    obj.detachEvent("onpropertychange", this._spellCheck);
                }
            } else {//非IE
                if (bAdd) {
                    obj.addEventListener("input", function(){_self._spellCheck(_self.readerApp)}, false);
                } else {
                    obj.removeEventListener("input", this._spellCheck, false);
                }
            }
        },



        init: function (readerApp, annotUIManager) {
        	var _self = this;
            var $mainFrame = $('#' + _self.readerApp.getAppId());
            $mainFrame.on('blur', '.typewriter-annot-edit', function (event) { 
                var obj = $('.typewriter-annot-edit');
                _self._addAndRemoveChangeValueEvent(obj.get(0), false);
                if (!WebPDF.Environment.webkit) {
                    $("#" + annotUIManager.getAnnotDivIDFromTypewriterAnnotRectDivID(obj.attr("id")))
                        .removeClass("typewriter-annot-edit-border");
                }
                obj.removeClass("typewriter-annot-edit").addClass("typewriter-annot-nor").attr('onselectstart', 'return false;');
                var annotObj = $("#" + annotUIManager.getAnnotDivIDFromTypewriterAnnotRectDivID(obj.attr("id")));
                //计算区域高度，如果高度不够，就向上扩展
                var targetRect = new WebPDF.PDFRect;
                targetRect.left = Math.max(0, parseFloat(annotObj.css("left")));
                targetRect.top = Math.max(0, parseFloat(annotObj.css("top")));
                targetRect.right = targetRect.left + annotObj.width();
                targetRect.bottom = targetRect.top + annotObj.height();

                var pageIndex = parseInt(annotObj.attr("page-index"));
                var annotName = annotObj.attr("annot-name");
                var docView = readerApp.getMainView().getDocView();
                var pageView = docView.getPageView(pageIndex);
                var pdfPage = pageView.getPDFPage();
                var annot = pdfPage.getAnnotByName(annotName);
                var pageRotate = (pdfPage.getPageRotate() * 90) % 360;
                var rotate = (annot.getRotate() % 360 + 360) % 360;
                var realRotate = Math.abs(rotate - pageRotate);
                var pageWidth = pageView.getPageViewWidth();
                var pageHeight = pageView.getPageViewHeight();
                //修改相应Rect的数据

                var pdfRect = annot.getRect();
                var pt2Pixel = readerApp.getPixelsPerPoint();
                var pt2PixelScale = pt2Pixel * pageView.getScale();
                if (obj.height() < obj.get(0).scrollHeight) {
                    var rotateMatrix = new WebPDF.PDFMatrix();
                    switch (realRotate) {
                        case 90:
                        {
                            targetRect.left = Math.max(0, targetRect.right - obj.get(0).scrollHeight);
                            var rectWidthStr = RectUtils.width(targetRect) + "px";
                            annotObj.css({
                                left: targetRect.left + "px",
                                width: rectWidthStr
                            });
                            //保存数据
                            pdfRect.left = targetRect.left / pt2PixelScale;
                            annot.setRect(pdfRect);
                            rotateMatrix.Translate(-targetRect.left, -targetRect.bottom, false);
                            rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                            rotateMatrix.Translate(targetRect.left, targetRect.bottom, false);
                        }
                            break;
                        case 180:
                        {
                            targetRect.bottom = Math.min(pageHeight, targetRect.top + obj.get(0).scrollHeight);
                            var rectHeightStr = RectUtils.height(targetRect) + "px";
                            annotObj.css({
                                bottom: targetRect.bottom + "px",
                                height: rectHeightStr
                            });
                            //保存数据
                            pdfRect.bottom = pdfPage.GetPageHeight() - targetRect.bottom / pt2PixelScale;
                            annot.SetRect(pdfRect);
                            rotateMatrix.Translate(-targetRect.right, -targetRect.bottom, false);
                            rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                            rotateMatrix.Translate(targetRect.right, targetRect.bottom, false);
                        }
                            break;
                        case 270:
                        {
                            targetRect.right = Math.min(pageWidth, targetRect.left + obj.get(0).scrollHeight);
                            var rectWidthStr = WebPDF.RectUtils.Width(targetRect) + "px";
                            annotObj.css({
                                right: targetRect.right + "px",
                                width: rectWidthStr
                            });
                            //保存数据
                            pdfRect.right = targetRect.right / pt2PixelScale;
                            annot.SetRect(pdfRect);
                            rotateMatrix.Translate(-targetRect.right, -targetRect.top, false);
                            rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                            rotateMatrix.Translate(targetRect.right, targetRect.top, false);
                        }
                            break;
                        default:
                        {
                            targetRect.top = Math.max(0, targetRect.bottom - obj.get(0).scrollHeight);
                            var rectHeightStr = RectUtils.height(targetRect) + "px";
                            annotObj.css({
                                top: targetRect.top + "px",
                                height: rectHeightStr
                            });
                            //保存数据
                            pdfRect.top = pdfPage.getPageHeight() - targetRect.top / pt2PixelScale;
                            annot.setRect(pdfRect);
                        }
                            break;
                    }

                    var rotateRect = rotateMatrix.TransFormRect(targetRect.left, targetRect.top, targetRect.right, targetRect.bottom);
                    targetRect.left = rotateRect[0];
                    targetRect.top = rotateRect[1];
                    targetRect.right = rotateRect[2];
                    targetRect.bottom = rotateRect[3];

                    var rectHeightStr = RectUtils.height(targetRect) + "px";
                    var rectWidthStr = RectUtils.width(targetRect) + "px";
                    obj.css({
                        left: targetRect.left + "px",
                        top: targetRect.top + "px",
                        width: rectWidthStr,
                        height: rectHeightStr,
                        "max-height": rectHeightStr
                    });


                    var timestamp = (new Date()).valueOf().toString();
                    annot.setModifyDate(timestamp);
                    pageView.setModified(true);
                    docView.setModified(true);
//                    _baseAnnotPlufgin.setSaveCommentBtnState(true);
                }
                return true;
            });
            
            $mainFrame.on('focus', '.typewriter-annot-nor', $.proxy(function (event) {                
                var obj = $(event.target);
                var annotHandlerMgr = _self.readerApp.getPluginByName(WebPDF.BASEANNOT_PLUGIN_NAME).getAnnotHandlerMgr();
               // annotHandlerMgr.clearSelection();
                var annotUIManager = annotHandlerMgr.getUIManager();
                var annotObj = $("#" + annotUIManager.getAnnotDivIDFromTypewriterAnnotRectDivID(obj.attr("id")));
                var annotHandler = annotHandlerMgr.getAnnotHandler(WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_TYPEWRITER);
                annotHandler.currentPageIndex = parseInt(annotObj.attr("page-index"));
                annotHandler.currentAnnotName = annotObj.attr("annot-name");
                annotHandler._spellCheck(_self.readerApp);
                annotHandler._addAndRemoveChangeValueEvent(obj.get(0), true);
                if (!WebPDF.Environment.webkit)
                	$("#" + annotUIManager.getAnnotDivIDFromTypewriterAnnotRectDivID(obj.attr("id"))).removeClass("fwr-annot-selected")
                	.addClass("typewriter-annot-edit-border");
                obj.removeClass("typewriter-annot-nor").addClass("typewriter-annot-edit").removeAttr('onselectstart');        
                return true;
            }, this));
        },
        onTypewriterAnnotEdit: function (pageView, annot) {
            var annotName = annot.getAnnotName();
            var annotHandlerMgr = this.readerApp.getPluginByName(WebPDF.BASEANNOT_PLUGIN_NAME).getAnnotHandlerMgr();
            var annotUIManager = annotHandlerMgr.getUIManager();
            var typeWriterAnnotRectDivId = annotUIManager.getTypewriterAnnotRectDivID(pageView, annotName);
            if (WebPDF.Environment.mobile) {
                $("#" + typeWriterAnnotRectDivId).focus();
            } else {
                if (WebPDF.Environment.ie8OrLower) {
                    setTimeout(function () {
                        $("#" + typeWriterAnnotRectDivId).focus();
                    }, 0);
                } else {
                	$("#" + typeWriterAnnotRectDivId).focus();
//                    document.getElementById(typeWriterAnnotRectDivId).focus();
                }
            }
        },
        _setTextareaCursorPosition: function (textarea, pos) {
            if (textarea.setSelectionRange) {
                // W3C
                textarea.setSelectionRange(pos, pos);
            } else if (textarea.createTextRange) {
                // IE
                var oR = textarea.createTextRange();
                // Fix bug :
                // In IE, if cursor position at the end of textarea, the setCursorPosition function don't work
                if (textarea.value.length === pos) {
                    oR.collapse(false);
                    oR.select();
                } else {
                    oR.select();
                }
            }
        },
        _calculateStrWidth: function (value, spanObj) {
            var width = 0;
            if (value != null && value != "") {
                spanObj.html(value.replace(/ /g, '&nbsp;'));
                width = spanObj.width();
                var lineNum = spanObj.height() / 10;            
                if (lineNum > 1) {
                    var lineCharNum = 1;                 
                    width = 0;
                    for (var i = 0; i < value.length; i++) {                     
                        spanObj.html(value.substr(lineCharNum * i, lineCharNum).replace(/ /g, '&nbsp;'));
                        width += spanObj.width();
                    }
                }
            }
            return width;
        },


        _spellCheck: function (readerApp) {//如果event == null,说明是编辑前的调整
//            if (event && WebPDF.Environment.ie && event.propertyName != "value")  {
//                return;
//            }
            var annotHandlerMgr = readerApp.getPluginByName(WebPDF.BASEANNOT_PLUGIN_NAME).getAnnotHandlerMgr();
            var annotUIManager = annotHandlerMgr.getUIManager();
            var annotHandler = annotHandlerMgr.getAnnotHandler(WebPDF.PDFData.TypewriterAnnotType.TYPEWRITERTYPE_TYPEWRITER);
            var docView = readerApp.getMainView().getDocView();
            var pageView = docView.getPageView(annotHandler.currentPageIndex);
            var obj = $("#" + annotUIManager.getTypewriterAnnotRectDivID(pageView, annotHandler.currentAnnotName));
            var jqTextAreaParent = obj.parent();
            var annotObj = $("#" + annotUIManager.getAnnotDivID(pageView, annotHandler.currentAnnotName));
            var id = "SpellCheckSpan" + (new Date()).valueOf().toString();
            var spanCode = '<span id= "' + id
                + '" style= "position: absolute;border:0;padding:0;line-height:10px;font-size:'
                + obj.css("font-size") + ';font-family:' + obj.css("font-family") + ';"></span>';
            obj.after(spanCode);
            var tmpSpanObj = $("#" + id);
            //解决空格测不出长度问题;
            var value = obj.val();
            var strArray = value.split('\n');
            var rowCount = strArray.length;
            var widthArray = new Array(rowCount);
            var maxLineWidth = 0;
            var minCharWidth = 0;
            for (var i = 0; i < rowCount; i++) {
                widthArray[i] = annotHandler._calculateStrWidth(strArray[i], tmpSpanObj);
                maxLineWidth = Math.max(maxLineWidth, widthArray[i]);
                if (strArray[i].length > 0) {
                    if (minCharWidth == 0) {
                        minCharWidth = widthArray[i] / strArray[i].length;
                    } else {
                        minCharWidth = Math.min(minCharWidth, widthArray[i] / strArray[i].length);
                    }
                }
            }
            tmpSpanObj.remove();
            var pdfPage = pageView.getPDFPage();
            var annot = pdfPage.getAnnotByName(annotHandler.currentAnnotName);
            var pageRotate = (pdfPage.getPageRotate() * 90) % 360;
            var rotate = (annot.getRotate() % 360 + 360) % 360;
            var realRotate = Math.abs(rotate - pageRotate);

            var pt2Pixel = this.readerApp.getPixelsPerPoint();
            var pt2PixelScale = pt2Pixel * pageView.getScale();
            var objLineHeight = parseFloat(obj.css("line-height"));
            //if (event == null) {
               // annot.setLineHeight(annot.getFontHeight());
               // objLineHeight = annot.getLineHeight() * pt2PixelScale;
               // obj.css("line-height", objLineHeight + "px");
            //}

            var pageWidth = pageView.getPageViewWidth();
            var pageHeight = pageView.getPageViewHeight();
            var srcRect = new PDFRect;
            var targetRect = new PDFRect;
            srcRect.left = Math.max(0, parseFloat(annotObj.css("left")));
            srcRect.top = Math.max(0, parseFloat(annotObj.css("top")));
            srcRect.right = srcRect.left + annotObj.width();
            srcRect.bottom = srcRect.top + annotObj.height();
            RectUtils.copy(srcRect, targetRect);

            //////先计算宽度
            var bChangeRect = false;
            if (maxLineWidth <= 0) {
                maxLineWidth = WebPDF.PDFData.TypewriteAnnotDefaultValue.NewAnnotWidth * pt2PixelScale;
            }
            //var newHeight = objLineHeight;
            var currentWidth = RectUtils.width(targetRect);
            if (realRotate == 90 || realRotate == 270){
                currentWidth = RectUtils.height(targetRect);
            }
            var needWidth = maxLineWidth - currentWidth + minCharWidth / 2;
            if (needWidth != 0) {
                switch (annot.getTextAlign()) {
                    case WebPDF.PDFData.TypeWriterTextAlignStyle.CENTERED: //居中
                    {
                        var needOneSideWidth = needWidth / 2;
                        switch (realRotate) {
                            case 0:
                            case 180:
                            {
                                needOneSideWidth = Math.min(needOneSideWidth, targetRect.left);
                                needOneSideWidth = Math.min(needOneSideWidth, pageWidth - targetRect.right);
                                targetRect.left -= needOneSideWidth;
                                targetRect.right += needOneSideWidth;
                            }
                                break;
                            case 90:
                            case 270:
                            {
                                needOneSideWidth = Math.min(needOneSideWidth, pageHeight - targetRect.bottom);
                                needOneSideWidth = Math.min(needOneSideWidth, targetRect.top);
                                targetRect.bottom += needOneSideWidth;
                                targetRect.top -= needOneSideWidth;
                            }
                                break;
                        }
                    }
                        break;
                    case WebPDF.PDFData.TypeWriterTextAlignStyle.RIGHT_JUSTIFIED: //居右
                    {

                        switch (realRotate) {
                            case 0:
                                targetRect.left = Math.max(0, targetRect.left - needWidth);
                                break;
                            case 90:
                                targetRect.bottom = Math.min(pageHeight, targetRect.bottom + needWidth);
                                break;
                            case 180:
                            {
                                targetRect.right = Math.min(pageWidth, targetRect.right + needWidth);
                            }
                                break;
                            case 270:
                            {
                                targetRect.top = Math.max(0, targetRect.top - needWidth);
                            }
                                break;
                        }
                    }
                        break;
                    default: //居左
                    {
                        switch (realRotate) {
                            case 0:
                                targetRect.right = Math.min(pageWidth, targetRect.right + needWidth);
                                break;
                            case 90:
                                targetRect.top = Math.max(0, targetRect.top - needWidth);
                                break;
                            case 180:
                            {
                                targetRect.left = Math.max(0, targetRect.left - needWidth);
                            }
                                break;
                            case 270:
                            {
                                targetRect.bottom = Math.min(pageHeight, targetRect.bottom + needWidth);
                            }
                                break;
                        }
                    }
                        break;
                }

                var tempRect = new PDFRect();
                RectUtils.copy(targetRect, tempRect);
                if (pageRotate != rotate) {
                    var rotateMatrix = new WebPDF.PDFMatrix();
                    switch (realRotate) {
                        case 90:
                        {
                            rotateMatrix.Translate(-tempRect.left, -tempRect.bottom, false);
                            rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                            rotateMatrix.Translate(tempRect.left, tempRect.bottom, false);
                        }
                            break;
                        case 180:
                        {
                            rotateMatrix.Translate(-tempRect.right, -tempRect.bottom, false);
                            rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                            rotateMatrix.Translate(tempRect.right, tempRect.bottom, false);
                        }
                            break;
                        case 270:
                        {
                            rotateMatrix.Translate(-tempRect.right, -tempRect.top, false);
                            rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                            rotateMatrix.Translate(tempRect.right, tempRect.top, false);
                        }
                            break;
                        default:
                            break;
                    }
                    var rotateRect = rotateMatrix.TransFormRect(tempRect.left, tempRect.top, tempRect.right, tempRect.bottom);
                    tempRect.left = rotateRect[0];
                    tempRect.top = rotateRect[1];
                    tempRect.right = rotateRect[2];
                    tempRect.bottom = rotateRect[3];
                    newHeight = RectUtils.height(tempRect);
                }

                var rectWidthStr = RectUtils.width(tempRect) + "px";
                if (WebPDF.Environment.ie8OrLower) {
                    jqTextAreaParent.css({
                        left: targetRect.left + "px",
                        top: targetRect.left + "px",
                        width: RectUtils.width(targetRect) + "px",
                        height: RectUtils.height(targetRect) + "px"
                    });
                    obj.css({
                        width: rectWidthStr,
                       // "max-width": rectWidthStr
                    });
                }
                else {
                    obj.css({
                        left: tempRect.left + "px",
                        width: rectWidthStr,
                       // "max-width": rectWidthStr
                    });
                }
                bChangeRect = true;
            }

            //////再计算高度
            obj.css({
                height: objLineHeight + "px",
                //"max-height": objLineHeight + "px"
            });

            switch (realRotate) {
                case 90:
                {
                    var desRight = Math.min(pageWidth, targetRect.left + obj.get(0).scrollHeight);
                    if (targetRect.right != desRight) {
                        targetRect.right = desRight;
                        bChangeRect = true;
                    }
                }
                    break;
                case 180:
                {
                    var desTop = Math.max(0, targetRect.bottom - obj.get(0).scrollHeight);
                    if (targetRect.top != desTop) {
                        targetRect.top = desTop;
                        bChangeRect = true;
                    }
                }
                    break;
                case 270:
                {
                    var desLeft = Math.max(0, targetRect.right - obj.get(0).scrollHeight);
                    if (targetRect.left != desLeft) {
                        targetRect.left = desLeft;
                        bChangeRect = true;
                    }
                }
                    break;
                default:
                {
                    var desBottom = Math.min(pageHeight, targetRect.top + obj.get(0).scrollHeight);
                    if (targetRect.bottom != desBottom) {
                        targetRect.bottom = desBottom;
                        bChangeRect = true;
                    }

                }
                    break;
            }


            if (bChangeRect) {
                var offsetLeft = targetRect.left - srcRect.left,
                    offsetRight = targetRect.right - srcRect.right,
                    //offsetTop = targetRect.top - srcRect.top,
                    offsetBottom = targetRect.bottom - srcRect.bottom;
                RectUtils.copy(targetRect, srcRect);

                //保存数据
                targetRect.left = targetRect.left / pt2PixelScale;
                targetRect.top = pdfPage.getPageHeight() - targetRect.top / pt2PixelScale;
                targetRect.right = targetRect.right / pt2PixelScale;
                targetRect.bottom = pdfPage.getPageHeight() - targetRect.bottom / pt2PixelScale;
                RectUtils.normalize(targetRect);
                annot.setRect(targetRect);
                annot.setContents(value);
                var timestamp = (new Date()).valueOf().toString();
                annot.setModifyDate(timestamp);
//                pdfPage.setModified(true);
                docView.setModified(true);
//                _baseAnnotPlugin.setSaveCommentBtnState(true);

                //计算并更新滚动条
                var jqPagesContainerDiv = $("#" + docView.getDocViewContainerID());
                var visibleHeight = jqPagesContainerDiv.height();
                var visibleWidth = jqPagesContainerDiv.width();
                var contentPanelOffset = jqPagesContainerDiv.offset();
                var jqPageContainer = $("#" + pageView.getPageViewContainerID());
                var page_pos = jqPageContainer.offset();
                var scrollApi = pageView.getDocView().getScrollApi();
                if (scrollApi != null) {
                    visibleHeight -= scrollApi.getScrollBarHeight();
                    visibleWidth -= scrollApi.getScrollBarWidth();
                    if (false) {
                        this._setTextareaCursorPosition(obj.get(0), value.length);
                        if (contentPanelOffset.left >= page_pos.left + srcRect.left) {
                            var offsetX = page_pos.left + srcRect.left - contentPanelOffset.left - 5;
                            scrollApi.scrollByX(offsetX);
                        } else if (contentPanelOffset.left + visibleWidth <= page_pos.left + srcRect.right) {
                            var offsetX = page_pos.left + srcRect.right - contentPanelOffset.left - visibleWidth + 5;
                            scrollApi.scrollByX(offsetX);
                        }

                        if (contentPanelOffset.top >= page_pos.top + srcRect.bottom - objLineHeight) {
                            var offsetY = page_pos.top + srcRect.top - objLineHeight - contentPanelOffset.top - 5;
                            scrollApi.scrollByY(offsetY);
                        } else if (contentPanelOffset.top + visibleHeight <= page_pos.top + srcRect.bottom) {
                            var offsetY = page_pos.top + srcRect.bottom - contentPanelOffset.top - visibleHeight + 5;
                            scrollApi.scrollByY(offsetY);
                        }
                    } else {
                        //Y
                        if (offsetBottom > 0) {
                            if (contentPanelOffset.top + visibleHeight <= page_pos.top + srcRect.bottom) {
                                scrollApi.scrollByY(offsetBottom + 5);
                            }
                        } else if (offsetBottom < 0) {
                            if (contentPanelOffset.top >= page_pos.top + srcRect.bottom - objLineHeight) {
                                var minOffsetY = Math.min(contentPanelOffset.top - (page_pos.top + srcRect.top),
                                        contentPanelOffset.top + visibleHeight - (page_pos.top + srcRect.bottom));
                                var offsetY = Math.min(offsetBottom, -minOffsetY);
                                scrollApi.scrollByY(offsetY - 5);
                            }
                        }
                        //X
                        switch (annot.getTextAlign()) {
                            case WebPDF.PDFData.TypeWriterTextAlignStyle.RIGHT_JUSTIFIED: //居右
                            {
                                if (offsetLeft > 0) {
                                    if (contentPanelOffset.left + visibleWidth <= page_pos.left + srcRect.right) {
                                        var minOffsetX = Math.min(page_pos.left + srcRect.right - (contentPanelOffset.left + visibleWidth),
                                                page_pos.left + srcRect.left - contentPanelOffset.left);
                                        var offsetX = Math.max(offsetLeft, minOffsetX);
                                        scrollApi.scrollByX(offsetX + 5);
                                    }
                                } else if (offsetLeft < 0) {
                                    if (contentPanelOffset.left >= page_pos.left + srcRect.left) {
                                        scrollApi.scrollByX(offsetLeft - 5);
                                    }
                                }
                            }
                                break;
                            default: //居左 居中
                            {
                                if (offsetRight > 0) {
                                    if (contentPanelOffset.left + visibleWidth <= page_pos.left + srcRect.right) {
                                        scrollApi.scrollByX(offsetRight + 5);
                                    }
                                } else if (offsetRight < 0) {
                                    if (contentPanelOffset.left >= page_pos.left + srcRect.left) {
                                        var minOffsetX = Math.min(contentPanelOffset.left + visibleWidth -
                                                (page_pos.left + srcRect.right),
                                                contentPanelOffset.left - (page_pos.left + srcRect.left));
                                        var offsetX = Math.min(offsetRight, -minOffsetX);
                                        scrollApi.scrollByX(offsetX - 5);
                                    }
                                }
                            }
                                break;
                        }
                    }
                }
            }

            //修改相应Rect的数据
            var rectWidthStr = RectUtils.width(srcRect)  +2 +"px";
            var rectHeightStr = RectUtils.height(srcRect)  + 2+ "px";        
            annotObj.css({
                left: srcRect.left + "px",
                top: srcRect.top + "px",
                width: rectWidthStr,
                height: rectHeightStr
            });
            if (WebPDF.Environment.ie8OrLower) {
                jqTextAreaParent.css({
                    left: srcRect.left + "px",
                    top: srcRect.top + "px",
                    width: rectWidthStr,
                    height: rectHeightStr
                });
            }
            if (pageRotate != rotate) {
                var rotateMatrix = new WebPDF.PDFMatrix();
                switch (realRotate) {
                    case 90:
                    {
                        rotateMatrix.Translate(-srcRect.left, -srcRect.bottom, false);
                        rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                        rotateMatrix.Translate(srcRect.left, srcRect.bottom, false);
                    }
                        break;
                    case 180:
                    {
                        rotateMatrix.Translate(-srcRect.right, -srcRect.bottom, false);
                        rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                        rotateMatrix.Translate(srcRect.right, srcRect.bottom, false);
                    }
                        break;
                    case 270:
                    {
                        rotateMatrix.Translate(-srcRect.right, -srcRect.top, false);
                        rotateMatrix.Rotate(Math.PI / 180 * realRotate, false);
                        rotateMatrix.Translate(srcRect.right, srcRect.top, false);
                    }
                        break;
                    default:
                        break;
                }
                var rotateRect = rotateMatrix.TransFormRect(srcRect.left, srcRect.top, srcRect.right, srcRect.bottom);
                srcRect.left = rotateRect[0];
                srcRect.top = rotateRect[1];
                srcRect.right = rotateRect[2];
                srcRect.bottom = rotateRect[3];
            }
            rectWidthStr = RectUtils.width(srcRect) + "px";
            rectHeightStr = RectUtils.height(srcRect) + "px";
            if (WebPDF.Environment.ie8OrLower) {
                obj.css({
                    width: rectWidthStr,
                    height: rectHeightStr,
                    //"max-width": rectWidthStr,
                   // "max-height": rectHeightStr
                });
                
                obj.parent().css({
                    width: rectWidthStr,
                    height: rectHeightStr,
                })
            }
            else {
                obj.css({                  
                    width: rectWidthStr,
                    height: rectHeightStr,
                   // "max-width": rectWidthStr,
                    //"max-height": rectHeightStr
                });
                obj.parent().css({
                    width: rectWidthStr,
                    height: rectHeightStr,
                })
            }
        }
    };

    return WebPDF.TypewriterAnnotHandler;
});